﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace OnLineExam.Web.Services
{

	public class UserAnswerService
	{
		private readonly Data.OnlineExamEntities _db;
		private readonly Data.EfRepository<Data.UserAnswer> _userAnswerRepository;
		private readonly Data.EfRepository<Data.Score> _scoreRepository;
		private readonly Data.EfRepository<Data.Paper> _paperRepository;
		private readonly Data.EfRepository<Data.PaperInfo> _paperInfoRepository;

		public UserAnswerService()
		{
			_db = new Data.OnlineExamEntities();
			_userAnswerRepository = new Data.EfRepository<Data.UserAnswer>(_db);
			_scoreRepository = new Data.EfRepository<Data.Score>(_db);

			_paperRepository = new Data.EfRepository<Data.Paper>(_db);

			_paperInfoRepository = new Data.EfRepository<Data.PaperInfo>(_db);
		}

		public Data.Score SubmitPaper(int scoreId, int paperId, string userId, List<Models.UserAnswerSubmitModel> values)
		{

			var toAddUserAnswer = new List<Data.UserAnswer>();

            //初始化一条成绩记录
            var score = new Data.Score();
            if (scoreId > 0)
            {
                score = _scoreRepository.GetById(scoreId);

            }
            else
            {
                score = _scoreRepository.Insert4Result(new Data.Score
                {
                    PaperID = paperId,
                    CourseID = 0,
                    DepID = 0,
                    ExamTime = DateTime.Now,
                    FillBlankProblemMark = 0,
                    JudgeProblemMark = 0,
                    MultiProblemMark = 0,
                    QuestionProblemMark = 0,
                    SingleProblemMark = 0,
                    UserID = userId,
                    UserScore = 0
                });
            }
			 

			foreach (var item in values)
			{
				var temp = new Data.UserAnswer
				{
					ExamTime = DateTime.Now,
					Mark = 0,
					PaperID = paperId,
					ScoreID = score.ID,
					UserMark = 0,
					TitleID = item.ItemId,
					UserAnswer1 = item.UserValue,
					UserID = userId,
					Type = Data.Paper.GetQuestionType(item.QuestionType)

				};

				toAddUserAnswer.Add(temp);

			}

			_userAnswerRepository.Insert(toAddUserAnswer);
			UpdateScore(score.ID);
			return score;
		}



		public void UpdateScore(int scoreId)
		{
			var score = _scoreRepository.GetById(scoreId);
			var paperInfos = _paperInfoRepository.TableNoTracking.Where(s=>s.PaperId==score.PaperID).ToList();

			var userValues = _userAnswerRepository.Table.Where(s => s.ScoreID == scoreId && s.UserMark == 0) ;

			var spList = _db.SingleProblem.AsNoTracking().Where(s => s.PaperID == score.PaperID).ToList();
			var mpList = _db.MultiProblem.AsNoTracking().Where(s => s.PaperID == score.PaperID).ToList();
			var jpList = _db.JudgeProblem.AsNoTracking().Where(s => s.PaperID == score.PaperID).ToList();


			var sMark = paperInfos.FirstOrDefault(s => s.QuestionType == Data.Paper.GetQuestionType(Data.QuestionType.Single)).Mark;
			var mMark = paperInfos.FirstOrDefault(s => s.QuestionType == Data.Paper.GetQuestionType(Data.QuestionType.Multi)).Mark;
			var jMark = paperInfos.FirstOrDefault(s => s.QuestionType == Data.Paper.GetQuestionType(Data.QuestionType.Judge)).Mark;

			foreach (var item in userValues)
			{
				var tempType = Data.Paper.GetQuestionTypeEnum(item.Type);
				switch (tempType)
				{
					case Data.QuestionType.Single:
						item.Mark = sMark;
						item.UserMark = spList.Any(s => s.ID == item.TitleID && s.Answer == item.UserAnswer1) ? item.Mark : 0;
						break;
					case Data.QuestionType.Multi:
						item.Mark = mMark;
						item.UserMark = mpList.Any(s => s.ID == item.TitleID && s.Answer == item.UserAnswer1) ? item.Mark : 0;
						break;
					case Data.QuestionType.Judge:
						item.Mark = jMark;
                        if (jpList.Any(s => s.ID == item.TitleID))
                         {
                            var tempJP = jpList.First(s => s.ID == item.TitleID);
                            if (tempJP.Answer)
                            {
                                item.UserMark= item.UserAnswer1 == "正确"?jMark:0;
                            }
                            else
                            {
                                item.UserMark = item.UserAnswer1 == "错误" ? jMark:0;

                            }
                        }
						//item.UserMark = jpList.Any(s => s.ID == item.TitleID && s.Answer == (item.UserAnswer1 == "正确")) ? item.Mark : 0;
						break;
					case Data.QuestionType.Fill:
						break;
					case Data.QuestionType.Qustion:
						break;
					case Data.QuestionType.Other:
						break;
					default:
						break;
				}
			}
			score.UserScore = userValues.ToList().Sum(s=>s.UserMark);
			_scoreRepository.Update(score);
			_userAnswerRepository.Update(userValues);

		}
	}
}